<template>
  <div class="purchase-detail">
    <!-- 筛选区域 -->
    <el-form :model="form" inline class="filter-form" label-width="80px">
      <!-- 日期范围 -->
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="form.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          :default-value="[new Date('2025-06-01'), new Date('2025-06-24')]"
        />
      </el-form-item>

      <!-- 供应商筛选（弹窗） -->
      <el-form-item label="供应商">
        <el-input
          v-model="form.supplier"
          placeholder="请选择供应商"
          readonly
          @click="supplierDialogVisible = true"
        />
      </el-form-item>

      <!-- 业务员筛选（弹窗） -->
      <el-form-item label="业务员">
        <el-input
          v-model="form.salesman"
          placeholder="请选择业务员"
          readonly
          @click="salesmanDialogVisible = true"
        />
      </el-form-item>

      <!-- 商品筛选（弹窗） -->
      <el-form-item label="商品">
        <el-input
          v-model="form.goods"
          placeholder="请选择商品"
          readonly
          @click="goodsDialogVisible = true"
        />
      </el-form-item>

      <!-- 查询按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>

      <!-- 展开条件 -->
      <el-form-item>
        <el-dropdown trigger="click">
          <el-button type="text" icon="el-icon-arrow-down">展开条件</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item>高级筛选</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="success" @click="handleExport">导出</el-button>
      <el-button type="info" @click="handlePrint">打印</el-button>
    </div>

    <!-- 采购明细表（含合计行） -->
    <el-table
      :data="computedTableData"
      border
      show-summary
      :summary-method="calcSummary"
      :header-cell-style="{ background: '#F8F9FA' }"
    >
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="sp_id" label="商品ID" width="100" />
      <el-table-column prop="brand_id" label="品牌ID" width="100" />
      <el-table-column prop="price" label="单价" width="100" align="right" />
      <el-table-column prop="qty" label="数量" width="100" align="right" />
      <el-table-column prop="unit_id" label="单位ID" width="100" />
      <el-table-column
        prop="amount"
        label="金额（不含税）"
        width="120"
        align="right"
      />
      <el-table-column prop="remark" label="备注" width="150" />
      <el-table-column prop="order_no" label="订单编号" width="150" />
      <el-table-column prop="is_gift" label="赠品" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.is_gift ? 'success' : 'info'">
            {{ scope.row.is_gift ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="unstock_qty"
        label="未入库数量"
        width="120"
        align="right"
      />
      <el-table-column
        prop="related_sale_order"
        label="关联销货订单号"
        width="180"
      />
      <el-table-column
        prop="tax_price"
        label="含税单价"
        width="120"
        align="right"
      />
      <el-table-column
        prop="discounted_tax_price"
        label="折后含税单价"
        width="140"
        align="right"
      />
      <el-table-column
        prop="discount_rate"
        label="折扣率(%)"
        width="100"
        align="right"
      />
      <el-table-column prop="discount" label="折扣" width="100" align="right" />
      <el-table-column
        prop="discount_amt"
        label="折扣额"
        width="100"
        align="right"
      />
      <el-table-column
        prop="discounted_price"
        label="折后单价"
        width="120"
        align="right"
      />
      <el-table-column
        prop="tax_rate"
        label="税率(%)"
        width="100"
        align="right"
      />
      <el-table-column prop="tax_amt" label="税额" width="100" align="right" />
      <el-table-column
        prop="total_amount"
        label="价税合计"
        width="120"
        align="right"
      />
      <el-table-column
        prop="purchase_cost"
        label="采购费用"
        width="120"
        align="right"
      />
      <el-table-column prop="supplier_name" label="供应商" width="150" />
      <el-table-column prop="salesman_name" label="业务员" width="120" />
    </el-table>

    <!-- 供应商选择弹窗 -->
    <el-dialog title="选择供应商" v-model="supplierDialogVisible" width="600px">
      <el-form :model="supplierSearch" inline class="mb-4">
        <el-form-item label="搜索">
          <el-input
            v-model="supplierSearch.keyword"
            placeholder="供应商编号/名称/联系人"
            clearable
            @keyup.enter="searchSuppliers"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="supplierSearch.showForbidden"
            >显示禁用供应商</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSuppliers">查询</el-button>
          <el-button @click="resetSupplierSearch">刷新</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="supplierList"
        border
        @selection-change="handleSupplierSelection"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="编号" width="120" />
        <el-table-column prop="name" label="名称" width="200" />
        <el-table-column prop="type" label="类别" width="120" />
        <el-table-column
          prop="initialPayable"
          label="期初应付款"
          width="150"
          align="right"
        />
      </el-table>

      <div class="dialog-footer mt-4">
        <el-pagination
          @size-change="handleSupplierSizeChange"
          @current-change="handleSupplierCurrentChange"
          :current-page="supplierPage.current"
          :page-sizes="[10, 20, 50]"
          :page-size="supplierPage.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="supplierTotal"
          style="float: left"
        ></el-pagination>
        <el-button @click="supplierDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSupplier">确定</el-button>
      </div>
    </el-dialog>

    <!-- 业务员选择弹窗 -->
    <el-dialog title="选择业务员" v-model="salesmanDialogVisible" width="600px">
      <el-form :model="salesmanSearch" inline class="mb-4">
        <el-form-item label="搜索">
          <el-input
            v-model="salesmanSearch.keyword"
            placeholder="职员编号/名称"
            clearable
            @keyup.enter="searchSalesmen"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="salesmanSearch.showForbidden"
            >显示禁用职员</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchSalesmen">查询</el-button>
          <el-button @click="resetSalesmanSearch">刷新</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="salesmanList"
        border
        @selection-change="handleSalesmanSelection"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="code" label="职员编号" width="120" />
        <el-table-column prop="name" label="职员名称" width="200" />
      </el-table>

      <div class="dialog-footer mt-4">
        <el-pagination
          @size-change="handleSalesmanSizeChange"
          @current-change="handleSalesmanCurrentChange"
          :current-page="salesmanPage.current"
          :page-sizes="[10, 20, 50]"
          :page-size="salesmanPage.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="salesmanTotal"
          style="float: left"
        ></el-pagination>
        <el-button @click="salesmanDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSalesman">确定</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择弹窗 -->
    <el-dialog title="选择商品" v-model="goodsDialogVisible" width="800px">
      <el-form :model="goodsSearch" inline class="mb-4">
        <el-form-item label="搜索">
          <el-input
            v-model="goodsSearch.keyword"
            placeholder="商品编号/名称/型号/品牌"
            clearable
            @keyup.enter="searchGoods"
          />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="goodsSearch.warehouse" placeholder="(空)">
            <el-option label="空" value=""></el-option>
            <el-option label="主仓库" value="main"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="goodsSearch.showZeroStock"
            >零库存商品</el-checkbox
          >
          <el-checkbox v-model="goodsSearch.showForbidden"
            >显示禁用商品</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchGoods">查询</el-button>
          <el-button @click="resetGoodsSearch">刷新</el-button>
        </el-form-item>
      </el-form>

      <div class="goods-container">
        <!-- 商品表格 -->
        <div class="goods-table">
          <el-table
            :data="goodsList"
            border
            @selection-change="handleGoodsSelection"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column label="图片" width="60">
              <template #default="scope">
                <el-image
                  v-if="scope.row.image"
                  :src="scope.row.image"
                  style="width: 40px; height: 40px"
                  fit="cover"
                />
                <span v-else class="no-img">无图</span>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="商品编号" width="120" />
            <el-table-column prop="brand" label="品牌" width="100" />
            <el-table-column prop="origin" label="产地" width="100" />
            <el-table-column prop="name" label="商品名称" width="200" />
          </el-table>

          <div class="dialog-footer mt-2">
            <el-pagination
              @size-change="handleGoodsSizeChange"
              @current-change="handleGoodsCurrentChange"
              :current-page="goodsPage.current"
              :page-sizes="[10, 20, 50]"
              :page-size="goodsPage.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="goodsTotal"
              style="float: left"
            ></el-pagination>
          </div>
        </div>

        <!-- 商品分类树 -->
        <div class="goods-category">
          <el-tree
            :data="categoryTree"
            :props="treeProps"
            default-expand-all
            show-checkbox
            @check="handleCategoryCheck"
          />
        </div>
      </div>

      <div class="dialog-footer mt-4">
        <el-button @click="goodsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGoods">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "PurchaseDetailTable",
  data() {
    return {
      // 筛选表单
      form: {
        dateRange: ["2025-06-01", "2025-06-24"],
        supplier: "",
        salesman: "",
        goods: "",
      },

      // 原始数据（动态计算衍生字段）
      rawTableData: [
        {
          id: 1,
          sp_id: "SP001",
          brand_id: "B001",
          price: 100, // 不含税单价
          qty: 10,
          unit_id: "U001",
          remark: "常规采购",
          order_no: "PO20250601",
          is_gift: false,
          unstock_qty: 2,
          related_sale_order: "SO20250601",
          discount_rate: 5, // 折扣率（%）
          tax_rate: 13, // 税率（%）
          purchase_cost: 50,
          supplier_name: "供应商A",
          salesman_name: "业务员甲",
        },
        {
          id: 2,
          sp_id: "SP002",
          brand_id: "B002",
          price: 50,
          qty: 20,
          unit_id: "U002",
          remark: "赠品单",
          order_no: "PO20250602",
          is_gift: true,
          unstock_qty: 0,
          related_sale_order: "SO20250602",
          discount_rate: 5,
          tax_rate: 13,
          purchase_cost: 30,
          supplier_name: "供应商B",
          salesman_name: "业务员乙",
        },
        {
          id: 3,
          sp_id: "SP003",
          brand_id: "B003",
          price: 200,
          qty: 5,
          unit_id: "U003",
          remark: "批量采购",
          order_no: "PO20250603",
          is_gift: false,
          unstock_qty: 1,
          related_sale_order: "SO20250603",
          discount_rate: 8,
          tax_rate: 13,
          purchase_cost: 80,
          supplier_name: "供应商C",
          salesman_name: "业务员丙",
        },
        {
          id: 4,
          sp_id: "SP004",
          brand_id: "B004",
          price: 80,
          qty: 15,
          unit_id: "U004",
          remark: "促销采购",
          order_no: "PO20250604",
          is_gift: false,
          unstock_qty: 3,
          related_sale_order: "SO20250604",
          discount_rate: 3,
          tax_rate: 13,
          purchase_cost: 40,
          supplier_name: "供应商D",
          salesman_name: "业务员丁",
        },
        {
          id: 5,
          sp_id: "SP005",
          brand_id: "B005",
          price: 150,
          qty: 8,
          unit_id: "U005",
          remark: "紧急采购",
          order_no: "PO20250605",
          is_gift: false,
          unstock_qty: 0,
          related_sale_order: "SO20250605",
          discount_rate: 0,
          tax_rate: 13,
          purchase_cost: 60,
          supplier_name: "供应商E",
          salesman_name: "业务员戊",
        },
      ],

      // 供应商弹窗数据
      supplierDialogVisible: false,
      supplierSearch: { keyword: "", showForbidden: false },
      supplierList: [
        { code: "G0001", name: "供应商A", type: "食品", initialPayable: 5000 },
        { code: "G0002", name: "供应商B", type: "百货", initialPayable: 3000 },
        { code: "G0003", name: "供应商C", type: "饮品", initialPayable: 8000 },
        { code: "G0004", name: "供应商D", type: "零食", initialPayable: 2000 },
        { code: "G0005", name: "供应商E", type: "生鲜", initialPayable: 6000 },
      ],
      supplierPage: { current: 1, size: 10 },
      supplierTotal: 5,
      selectedSuppliers: [],

      // 业务员弹窗数据
      salesmanDialogVisible: false,
      salesmanSearch: { keyword: "", showForbidden: false },
      salesmanList: [
        { code: "D001", name: "业务员甲" },
        { code: "D002", name: "业务员乙" },
        { code: "D003", name: "业务员丙" },
        { code: "D004", name: "业务员丁" },
        { code: "D005", name: "业务员戊" },
      ],
      salesmanPage: { current: 1, size: 10 },
      salesmanTotal: 5,
      selectedSalesmen: [],

      // 商品弹窗数据
      goodsDialogVisible: false,
      goodsSearch: {
        keyword: "",
        warehouse: "",
        showZeroStock: true,
        showForbidden: true,
      },
      goodsList: [
        {
          code: "SP001",
          name: "商品1",
          brand: "品牌A",
          origin: "中国",
          image: "",
        },
        {
          code: "SP002",
          name: "商品2",
          brand: "品牌B",
          origin: "中国",
          image: "",
        },
        {
          code: "SP003",
          name: "商品3",
          brand: "品牌C",
          origin: "中国",
          image: "",
        },
        {
          code: "SP004",
          name: "商品4",
          brand: "品牌D",
          origin: "中国",
          image: "",
        },
        {
          code: "SP005",
          name: "商品5",
          brand: "品牌E",
          origin: "中国",
          image: "",
        },
      ],
      goodsPage: { current: 1, size: 20 },
      goodsTotal: 5,
      selectedGoods: [],
      categoryTree: [
        {
          label: "全部",
          children: [{ label: "食品" }, { label: "饮品" }, { label: "百货" }],
        },
      ],
      treeProps: { children: "children", label: "label" },
    };
  },
  computed: {
    // 动态计算衍生字段（含税价、折后价等）
    computedTableData() {
      return this.rawTableData.map((item) => {
        // 含税单价 = 不含税单价 × (1 + 税率/100)
        item.tax_price = item.price * (1 + item.tax_rate / 100);
        // 折后单价 = 不含税单价 × (1 - 折扣率/100)
        item.discounted_price = item.price * (1 - item.discount_rate / 100);
        // 折后含税单价 = 含税单价 × (1 - 折扣率/100)
        item.discounted_tax_price =
          item.tax_price * (1 - item.discount_rate / 100);
        // 金额（不含税）= 不含税单价 × 数量
        item.amount = item.price * item.qty;
        // 折扣额 = 金额（不含税） × 折扣率/100
        item.discount_amt = item.amount * (item.discount_rate / 100);
        // 税额 = 金额（不含税） × 税率/100
        item.tax_amt = item.amount * (item.tax_rate / 100);
        // 价税合计 = 金额（不含税） + 税额
        item.total_amount = item.amount + item.tax_amt;
        return item;
      });
    },
  },
  methods: {
    // 查询逻辑：根据筛选条件过滤数据
    handleQuery() {
      const filtered = this.computedTableData.filter((item) => {
        const inDateRange = item.order_no.includes("2025-06"); // 简化日期匹配，实际需解析订单日期
        const supplierMatch =
          !this.form.supplier ||
          item.supplier_name.includes(this.form.supplier);
        const salesmanMatch =
          !this.form.salesman ||
          item.salesman_name.includes(this.form.salesman);
        const goodsMatch =
          !this.form.goods ||
          item.sp_id.includes(this.form.goods) ||
          item.brand_id.includes(this.form.goods);
        return inDateRange && supplierMatch && salesmanMatch && goodsMatch;
      });
      this.$message.success(`共找到 ${filtered.length} 条数据`);
      // 实际应更新表格数据，此处演示过滤逻辑
      console.log("筛选结果：", filtered);
    },

    // 导出功能（示例）
    handleExport() {
      this.$message.info("导出功能待实现");
    },

    // 打印功能（示例）
    handlePrint() {
      this.$message.info("打印功能待实现");
    },

    // 表格合计计算
    calcSummary({ columns, data }) {
      const sums = [];
      columns.forEach((col, i) => {
        if (i === 0) {
          sums[i] = "合计:";
          return;
        }
        const prop = col.prop;
        if (
          [
            "qty",
            "amount",
            "tax_amt",
            "total_amount",
            "purchase_cost",
            "discount_amt",
          ].includes(prop)
        ) {
          sums[i] = data.reduce((acc, cur) => acc + (cur[prop] || 0), 0);
        } else {
          sums[i] = "";
        }
      });
      return sums;
    },

    // 供应商弹窗逻辑（省略重复代码，与之前示例一致）
    searchSuppliers() {},
    resetSupplierSearch() {},
    handleSupplierSelection() {},
    confirmSupplier() {
      this.form.supplier = this.selectedSuppliers
        .map((item) => item.name)
        .join("、");
      this.supplierDialogVisible = false;
    },
    handleSupplierSizeChange() {},
    handleSupplierCurrentChange() {},

    // 业务员弹窗逻辑（省略重复代码，与之前示例一致）
    searchSalesmen() {},
    resetSalesmanSearch() {},
    handleSalesmanSelection() {},
    confirmSalesman() {
      this.form.salesman = this.selectedSalesmen
        .map((item) => item.name)
        .join("、");
      this.salesmanDialogVisible = false;
    },
    handleSalesmanSizeChange() {},
    handleSalesmanCurrentChange() {},

    // 商品弹窗逻辑（省略重复代码，与之前示例一致）
    searchGoods() {},
    resetGoodsSearch() {},
    handleGoodsSelection() {},
    handleCategoryCheck() {},
    confirmGoods() {
      this.form.goods = this.selectedGoods.map((item) => item.code).join("、");
      this.goodsDialogVisible = false;
    },
    handleGoodsSizeChange() {},
    handleGoodsCurrentChange() {},
  },
};
</script>

<style scoped>
.purchase-detail {
  padding: 24px;
  background: #fff;
}

.filter-form {
  margin-bottom: 16px;
}

.action-bar {
  margin: 12px 0;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.el-table {
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-container {
  display: flex;
  gap: 20px;
}

.goods-table {
  flex: 1;
}

.goods-category {
  width: 250px;
}

.no-img {
  display: inline-block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background: #f5f7fa;
  border-radius: 4px;
  color: #999;
}
</style>